package lichtruong.bk.cse;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


public class GetDataReported extends ListActivity{

	// Variable
	int indexClick, leveluser;
	static double latitude, longitude;
	String infoDataReported[];
	String MAIL_REPORT;
	ArrayList<PR> DataReported = new ArrayList<PR>();
	ProgressDialog pDialog;
	
	ArrayList<PR> informationall = new ArrayList<PR>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		getLocationGPS();
		MAIL_REPORT = returnMail();
		new GetPointReported().execute();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		super.onOptionsItemSelected(item);
		optionSelect();
		return true;
	}
	
	private void optionSelect(){
		String login;
		Database getlevel = new Database(GetDataReported.this);
		getlevel.open();
		if(Integer.parseInt(getlevel.getData_USER().level) == 0){
			login = "                 Đăng Nhập     ";
			leveluser = Integer.parseInt(getlevel.getData_USER().level);
		}else{
			login = "                 Đăng Xuất     ";
			leveluser = Integer.parseInt(getlevel.getData_USER().level);
		}
		getlevel.close();
		CharSequence[] items = {"                   Đăng Ký ", login,"               Xem Tự Động   ", "          Báo Cáo Tắc Đường   "};
		new AlertDialog.Builder(this)
		.setTitle("   Danh Sách Lựa Chọn  ")
		.setItems(items, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if(which == 0){
					Intent register = new Intent(GetDataReported.this, Register.class);
					startActivity(register);
				}else if(which == 1){
					if(leveluser == 0){
						Intent login = new Intent(GetDataReported.this, Login.class);
						login.putExtra("back", "3");
						startActivity(login);
					}else{
						Database updateLevel = new Database(GetDataReported.this);
						updateLevel.open(); updateLevel.updateLevelUser("0"); updateLevel.close();
						Toast.makeText(getBaseContext(), "Đăng Xuất Thành Công", Toast.LENGTH_SHORT).show();
					}
				}else if(which == 2){
					Intent report = new Intent(GetDataReported.this, AuToGet.class);
					startActivity(report);
				}else{
					if(leveluser == 0){
						Intent login = new Intent(GetDataReported.this, Login.class);
						login.putExtra("back", "2");
						startActivity(login);
					}else{
						Intent report = new Intent(GetDataReported.this, Report.class);
						startActivity(report);
					}
				}
			}
		}).show();
		//.setMessage(message)
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		indexClick = position;
		stepOne();
	}
	
	public String returnMail() {
		Database getMail = new Database(GetDataReported.this);
		getMail.open();
		User mail_user = getMail.getData_USER();
		getMail.close();
		return mail_user.mail;
	}
	
	public void stepOne(){
		AlertDialog.Builder stepOneDialog = new AlertDialog.Builder(
				GetDataReported.this);
		stepOneDialog.setMessage(informationall.get(indexClick).info)
		.setTitle("  Địa Điểm Đang Tắc Đường")
		.setPositiveButton("Xem Chi Tiết", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				stepTwodotTwo();
			}
		})
		.setNegativeButton("Báo Tắc Đường", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Database getlevel = new Database(GetDataReported.this);
				getlevel.open();
				if(Integer.parseInt(getlevel.getData_USER().level) == 0){
					AlertDialog.Builder builderLogin = new AlertDialog.Builder(GetDataReported.this);
					builderLogin.setMessage("Bạn Phải Đăng Nhập Trước Khi Thực Hiện Chức Năng Báo Cáo")
							.setTitle("  Tin Nhắn Từ Blue Road  ")
							.setPositiveButton("Đồng Ý",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog,
												int which) {
											Intent login = new Intent(GetDataReported.this, Login.class);
											login.putExtra("back", "3");
											startActivity(login);
										}
									})
							.setNegativeButton("Hủy",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									}).setCancelable(false);
					builderLogin.show();
				}else{
					stepTwodotOne();
				}
				getlevel.close();
			}
		})
		.setNeutralButton("Hủy", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// no action
			}
		}).show();
	}
	
	public void stepTwodotOne(){
		AlertDialog.Builder stepTwodotOneDialog = new AlertDialog.Builder(
				GetDataReported.this);
		stepTwodotOneDialog.setTitle(" Bạn Hãy Chọn Kiểu Báo Cáo")
		.setPositiveButton("Đang Tắc Đường", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				UpDateDataToServer reportTypeOne = new UpDateDataToServer();
				reportTypeOne.reportToBlueRoad(informationall.get(indexClick).id,MAIL_REPORT, "1");
				Toast.makeText(getBaseContext(), "Báo Cáo Thành Công", Toast.LENGTH_SHORT).show();
			}
		})
		.setNegativeButton("Hết Tắc Đường", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				UpDateDataToServer reportTypeTwo = new UpDateDataToServer();
				reportTypeTwo.reportToBlueRoad(informationall.get(indexClick).id,MAIL_REPORT, "0");
				Toast.makeText(getBaseContext(), "Báo Cáo Thành Công", Toast.LENGTH_SHORT).show();
			}
		})
		.setNeutralButton("Hủy", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// no action
			}
		}).show();
	}
	
	public void stepTwodotTwo(){
		AlertDialog.Builder stepTwodotTwoDialog = new AlertDialog.Builder(
				GetDataReported.this);
		String TAndDate = informationall.get(indexClick).timenear;
		String timereportednew = (TAndDate).subSequence(0, 8).toString();
		String datereportednew = (TAndDate).subSequence(11, 21).toString();
		String timedropnew = (TAndDate).subSequence(24, TAndDate.length()).toString();
		
		String[] numberRe = (informationall.get(indexClick).numpr).split(":");
		String numberReported = "-> Số báo tắc đường : " + numberRe[0] + "\n" +
								"-> Báo cáo gần đây nhất lúc :" + "\n" + "       " + timereportednew + " - " + datereportednew;
		String numberDrop = String.valueOf(numberRe[1]);
		if(Integer.parseInt(numberDrop) == 0){
			numberDrop = "-> Chưa có báo hết tắc Đường";
		}else{
			numberDrop = "-> Số báo hết tắc đường : " + numberDrop + "\n" +
						 "-> Báo cáo gần đây nhất lúc :" + "\n" + "       " + timedropnew + " - " + datereportednew;
		}
		String info = "-> Địa Điểm : " + "\n" + "+ " + informationall.get(indexClick).info + "\n" +
					  numberReported + "\n" + numberDrop + "\n" +
					  "-> Bạn không lên đi qua địa điểm này trong khoảng " + informationall.get(indexClick).messagebl + " phút nữa";
		stepTwodotTwoDialog.setMessage(info)
		.setTitle("    Địa Điểm Đang Tắc Đường")
		.setPositiveButton("Xem Trên Bản Đồ", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String allId = "", allInfo = "",allLat = "", allLng = "", allNumr = "", allTimenear = "", allMessagebl = "";
				for(int i = 0; i < informationall.size(); i++){
					allId = allId + "-" + informationall.get(i).id;
					allInfo = allInfo + "-" + informationall.get(i).info;
					allLat = allLat + "-" + informationall.get(i).lat;
					allLng = allLng + "-" + informationall.get(i).lng;
					allNumr = allNumr + "-" + informationall.get(i).numpr;
					allTimenear = allTimenear + "-" + informationall.get(i).timenear;
					allMessagebl = allMessagebl + "-" + informationall.get(i).messagebl;
				}
				// Starting new intent
                Intent in = new Intent(getApplicationContext(),
                		ShowAllReported.class);
                // sending pid to next activity
                in.putExtra("allId", allId);
                in.putExtra("allInfo", allInfo);
                in.putExtra("allLat", allLat);
                in.putExtra("allLng", allLng);
                in.putExtra("allNumr", allNumr);
                in.putExtra("allTimenear", allTimenear);
                in.putExtra("allMessagebl", allMessagebl);
                in.putExtra("index", String.valueOf(indexClick));
                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
			}
		})
		.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// no action
			}
		}).show();
	}
	
	public void getLocationGPS(){
		menu locationGPS = new menu();
		double[] latlngCurrent = locationGPS.locationCurrent();
		latitude = latlngCurrent[0];
		longitude = latlngCurrent[1];
	}
	
	// get data point reported
		class GetPointReported extends AsyncTask<String, String, String> {
			// get data
			JSONArray infomations_point_report;
			JSONParser JsonParser = new JSONParser();
			private static final String URL_GETINFO = "http://lichcse.hol.es/reported.php";
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				pDialog = new ProgressDialog(GetDataReported.this);
				pDialog.setMessage("Please wait ...");
				pDialog.setIndeterminate(false);
				pDialog.setCancelable(true);
				pDialog.show();
			}
			
			@Override
			protected String doInBackground(String... args) {
				// Check for success tag
				int success;
				try {
					// Building Parameters
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("lat", String
							.valueOf(latitude)));
					params.add(new BasicNameValuePair("lng", String
							.valueOf(longitude)));
					// Posting user data to script
					JSONObject json = JsonParser.makeHttpRequest(URL_GETINFO,
							"POST", params);

					success = json.getInt("success"); // error

					if (success == 1) {

						infomations_point_report = json
								.getJSONArray("point_reported");

						for (int i = 0; i < infomations_point_report.length(); i++) {
							JSONObject l = infomations_point_report
									.getJSONObject(i);
							PR point = new PR();
							point.id = l.getString("id");
							point.info = l.getString("info");
							point.lat = l.getString("lat");
							point.lng = l.getString("lng");
							point.numpr = l.getString("numpr");
							point.timenear = l.getString("timenear");
							point.messagebl = l.getString("messagebl");
							informationall.add(point);
						}
					} else {
						
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				return null;
			}
			
			protected void onPostExecute(String file_url) {
				// dismiss the dialog once product deleted
				pDialog.dismiss();
				
				if(informationall.size() > 0){
					infoDataReported = new String[informationall.size()];
					for(int i = 0; i < informationall.size(); i++){
						infoDataReported[i] = informationall.get(i).info;
					}
					setListAdapter(new ArrayAdapter<String>(GetDataReported.this,
							android.R.layout.simple_list_item_1, infoDataReported));
				}else{
					AlertDialog.Builder notpointreported = new AlertDialog.Builder(
							GetDataReported.this);
					notpointreported.setTitle("  Tin Nhắn Từ Blue Road ")
					.setMessage("Hiện tại chưa có điểm nào trong" + "\n" + "   thành phố xảy ra tắc đường.")
					.setPositiveButton("Hủy", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent menu = new Intent(GetDataReported.this, menu.class);
							startActivity(menu);
						}
					})
					.setNegativeButton("Thử Lại", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent getdatareported = new Intent(GetDataReported.this, GetDataReported.class);
							startActivity(getdatareported);
						}
					}).show();
				}

			}
			
		}
}
